//
//  Validators.m
//  
//
//  Created by jiaching on 8/12/10.
//  Copyright (c) 2010 __MyCompanyName__. All rights reserved.
//

#import "Validators.h"
#import <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#import <LBFoundation/LBAddition.h>

@implementation Validators

+ (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {
    
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
    
    

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
    
//    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
//    
//    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
//
//    NSString *hash = [[NSString alloc] initWithData:[Validators base64DataforLowercaseData:HMAC] encoding:NSASCIIStringEncoding];
//    

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
    NSMutableString *HMACs = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [HMACs appendFormat:@"%02x", buffer[i]];
    }
    return [HMACs base64EncodedString];

}


#pragma mark - B64

+ (NSData *)base64DataForString:(NSString *)input {
    return [input dataUsingEncoding:NSASCIIStringEncoding];
}
//
//+ (NSString *)base64StringForString:(NSString *)input {
//    NSData * authData = [Validators base64DataForString:input];
//    return [authData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//}
//
//+ (NSString*)base64StringforData:(NSData* )theData{
//    return [[NSString alloc] initWithData:[Validators base64DataforData:theData] encoding:NSASCIIStringEncoding];
//}
//
//+ (NSData*)base64DataforLowercaseData:(NSData* )theData{
//    const uint8_t* input = (const uint8_t*)[theData bytes];
//    NSInteger length = [theData length];
//
//    static char table[] = "abcdefghijklmnopqrstuvwxyz0123456789";
//
//    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
//    uint8_t* output = (uint8_t*)data.mutableBytes;
//
//    NSInteger i;
//    for (i=0; i < length; i += 3) {
//        NSInteger value = 0;
//        NSInteger j;
//        for (j = i; j < (i + 3); j++) {
//            value <<= 8;
//
//            if (j < length) {
//                value |= (0xFF & input[j]);
//            }
//        }
//
//        NSInteger theIndex = (i / 3) * 4;
//        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
//        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
//        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
//        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
//    }
//
//    return data;
//}
//
//+ (NSData*)base64DataforData:(NSData* )theData{
//    const uint8_t* input = (const uint8_t*)[theData bytes];
//    NSInteger length = [theData length];
//
//    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
//
//    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
//    uint8_t* output = (uint8_t*)data.mutableBytes;
//
//    NSInteger i;
//    for (i=0; i < length; i += 3) {
//        NSInteger value = 0;
//        NSInteger j;
//        for (j = i; j < (i + 3); j++) {
//            value <<= 8;
//
//            if (j < length) {
//                value |= (0xFF & input[j]);
//            }
//        }
//
//        NSInteger theIndex = (i / 3) * 4;
//        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
//        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
//        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
//        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
//    }
//
//    return data;
//}
//
//+ (NSString *)decodeBase64String:(NSString *)base64String{
//
//    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
//    return [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
//
//}
//
//
//#pragma mark - Validations
//
//+ (BOOL)validateEmailString:(NSString*) email{
//    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
//    NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
//    return [regExPredicate evaluateWithObject:email];
//}
//
//+ (BOOL)validateBillAccountNumberString:(NSString*) accountNumber withRegex:(NSString*)regex{
//    NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//    return [regExPredicate evaluateWithObject:accountNumber];
//}
//
//+ (BOOL)checkNric:(NSString*)nric{
//
//    if(!nric) return NO;
//
//    NSString * strNric = [nric uppercaseString];
//  //  [[ApiClientManager sharedClient].secureLog log:@"strNRIC substring to 1:%@",[strNric substringToIndex:1]];
//
//    BOOL hasRequiredChar = NO;
//    if ([[strNric substringToIndex:1]isEqualToString:@"S"]  ||
//        [[strNric substringToIndex:1]isEqualToString:@"T"]) {
//        //Ignore checking for now if NRIC didnt start with S or T
//        hasRequiredChar = YES;
//    }
//    if (!hasRequiredChar) {
//        return YES;
//    }
//
//    if ( [strNric length] != 9 ) return NO;
//
//    // Format:  [S|T|F|G] [0-9]*7 [A-Z]
//    NSInteger totalNumber = 0;
//
//    // first digit you multiply by 2
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(1,1)] intValue] * 2);
//    // second multiply by 7
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(2,1)] intValue] * 7);
//    // third by 6
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(3,1)] intValue] * 6);
//    // fourth by 5
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(4,1)] intValue] * 5);
//    // fifth by 4
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(5,1)] intValue] * 4);
//    // sixth by 3
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(6,1)] intValue] * 3);
//    // seventh by 2
//    totalNumber = totalNumber + ([[strNric substringWithRange:NSMakeRange(7,1)] intValue] * 2);
//
//    // Then you add the totals together. So,[1]*2+[2]*7+[3]*6+[4]*5+[5]*4+[6]*3+[7]*2=106.
//
//    // If the first letter of the NRIC starts with T or G, add 4 to the total.
//    if( [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"T" ] ||
//       [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"G" ] ){
//        totalNumber = totalNumber + 4;
//    }
//
//    // Then you divide the number by 11 and get the remainder. 106/11=9r7
//    NSInteger remainder = totalNumber%11;
//
//    // 4) You can get the alphabet depending on the IC type (the first letter in the IC) using the code below:
//    NSString * result = nil;
//    if( [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"S" ] ||
//       [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"T" ] ){
//        //     If the IC starts with S or T: 0=J, 1=Z, 2=I, 3=H, 4=G, 5=F, 6=E, 7=D, 8=C, 9=B, 10=A
//        switch (remainder) {
//            case 0:{
//                result = @"J";
//                break;
//            }
//            case 1:{
//                result = @"Z";
//                break;
//            }
//            case 2:{
//                result = @"I";
//                break;
//            }
//            case 3:{
//                result = @"H";
//                break;
//            }
//            case 4:{
//                result = @"G";
//                break;
//            }
//            case 5:{
//                result = @"F";
//                break;
//            }
//            case 6:{
//                result = @"E";
//                break;
//            }
//            case 7:{
//                result = @"D";
//                break;
//            }
//            case 8:{
//                result = @"C";
//                break;
//            }
//            case 9:{
//                result = @"B";
//                break;
//            }
//            case 10:{
//                result = @"A";
//                break;
//            }
//        }
//    } else if( [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"F" ] ||
//              [[strNric substringWithRange:NSMakeRange(0,1)] isEqualToString:@"G" ] ){
//        // If the IC starts with F or G: 0=X, 1=W, 2=U, 3=T, 4=R, 5=Q, 6=P, 7=N, 8=M, 9=L, 10=K
//        switch (remainder) {
//            case 0:{
//                result = @"X";
//                break;
//            }
//            case 1:{
//                result = @"W";
//                break;
//            }
//            case 2:{
//                result = @"U";
//                break;
//            }
//            case 3:{
//                result = @"T";
//                break;
//            }
//            case 4:{
//                result = @"R";
//                break;
//            }
//            case 5:{
//                result = @"Q";
//                break;
//            }
//            case 6:{
//                result = @"P";
//                break;
//            }
//            case 7:{
//                result = @"N";
//                break;
//            }
//            case 8:{
//                result = @"M";
//                break;
//            }
//            case 9:{
//                result = @"L";
//                break;
//            }
//            case 10:{
//                result = @"K";
//                break;
//            }
//        }
//    }
//
//    // Validate
//    if( [[strNric substringWithRange:NSMakeRange(8,1)] isEqualToString:result ] ){
//        return YES;
//    } else {
//        return NO;
//    }
//}
//
//+ (NSInteger)currentAge:(NSDate*)dateOfBirth baseOn:(CurrentAgeType)currentAgeType{
//    if(dateOfBirth){
//        NSCalendar *calendar = [NSCalendar currentCalendar];
//
//        unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
//        NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[NSDate date]];
//        NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:dateOfBirth];
//
//        switch (currentAgeType) {
//            case CurrentAgeBasedOnDate:
//            {
//                if (([dateComponentsNow month] < [dateComponentsBirth month]) ||
//                    (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) {
//                    return [dateComponentsNow year] - [dateComponentsBirth year] - 1;
//                } else {
//                    return [dateComponentsNow year] - [dateComponentsBirth year];
//                }
//                break;
//
//            case CurrentAgeBasedOnYear:
//                    return [dateComponentsNow year] - [dateComponentsBirth year];
//
//                break;
//            default:
//                break;
//            }
//        }
//    }else{
//        return 0;
//    }
//}
//
//+ (NSDate*) firstBirthdayForAge:(NSUInteger)age{
//    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//
//    [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
//    NSDateComponents *components = [cal components:( NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone) fromDate:[NSDate date]];
//
//    [components setHour:0];
//    [components setMinute:0];
//    [components setSecond:0];
//    [components setDay:1];
//    [components setMonth:1];
//    [components setYear:[components year] - age];
//
//    return [cal dateFromComponents:components];
//}
//
//+ (NSString*) ordinalForNumber:(int)num{
//
//    int ones = num % 10;
//    double chkTen = floor( num/10);
//
//    int tens = (int)(chkTen) % 10 ;
//
//    NSString * suffix;
//
//    if (tens == 1) {
//        suffix = @"th";
//    }else {
//            switch (ones) {
//                case 1 : suffix = @"st"; break;
//                case 2 : suffix = @"nd"; break;
//                case 3 : suffix = @"rd"; break;
//                default : suffix = @"th";
//            }
//        }
//    return suffix;
//
//}
//
//+(BOOL)validatePassportExpiryDate:(NSString *)expiryDate {
//    BOOL isValid = NO;
//    NSDate *date;
//    if ([expiryDate containsString:@"Z"]) {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:dateFormatAPITZStyle];
//        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//       date = [dateFormatter dateFromString:expiryDate];
//    }else {
//
//        NSArray *separatedArray = [expiryDate componentsSeparatedByString:@"+"];
//        NSString *tempDateString = separatedArray.firstObject;
//
//        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
//
//        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
//
//        [dateFormatter setTimeZone:timeZone];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
//        date = [dateFormatter dateFromString:tempDateString];
//    }
//    NSDate * extractExpiryDate = [self extractDate:date];
//    NSDate * currentDate = [self extractDate:[NSDate date]];
//    if ([extractExpiryDate compare:currentDate] == 1 || [extractExpiryDate compare:currentDate] == 0) {
//        isValid = YES;
//    }
//    return isValid;
//
//
//}
//+(BOOL)validateUserBirthday:(NSString *)birthday{
//    BOOL isValid = NO;
//
//    NSDate *date;
//    if ([birthday containsString:@"Z"]) {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:dateFormatAPITZStyle];
//        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//        date = [dateFormatter dateFromString:birthday];
//    }else {
//
//        NSArray *separatedArray = [birthday componentsSeparatedByString:@"+"];
//        NSString *tempDateString = separatedArray.firstObject;
//
//        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
//
//        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
//
//        [dateFormatter setTimeZone:timeZone];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
//        date = [dateFormatter dateFromString:tempDateString];
//    }
//    NSDate * extractBirthdayDate = [self extractDate:date];
//    NSDate * currentDate = [self extractDate:[NSDate date]];
//    NSDate *targetDate = [extractBirthdayDate dateByAddingYears:12];
//     if ([targetDate compare:currentDate] == -1 || [targetDate compare:currentDate] == 0) {
//        isValid = YES;
//    }
//    return isValid;
//
//
//
//}
//
//+ (NSDate *)extractDate:(NSDate *)date {
//    //get seconds since 1970
//    NSTimeInterval interval = [date timeIntervalSince1970];
//    int daySeconds = 24 * 60 * 60;
//    //calculate integer type of days
//    NSInteger allDays = interval / daySeconds;
//    return [NSDate dateWithTimeIntervalSince1970:allDays * daySeconds];
//}
//
////-------------------------------
//#pragma mark - MOLWallet Validators
////-------------------------------
//+ (NSString *)convertMobileNumber:(NSString *)mobileNumber {
//    NSArray * filterList = @[@"+", @"-", @" "];
//
//    NSString * _mobileNumber = mobileNumber;
//    for (NSString * filter in filterList) {
//        _mobileNumber = [_mobileNumber stringByReplacingOccurrencesOfString:filter withString:@""];
//    }
//    return _mobileNumber;
//}
//
//+ (BOOL)validateMobileNumber:(NSString *)mobileNumber {
//    if (!mobileNumber) {
//        return NO;
//    }
//
//    return ([self convertMobileNumber:mobileNumber].length >= 10);
//}
//
//+ (BOOL)validatePassportNumber:(NSString *)passport {
//    BOOL valid = YES;
//
//    NSString * firstAlphabet = [passport substringToIndex:1];
//    NSString * restOfTheString = [passport substringFromIndex:1];
//
//    NSCharacterSet * alphabetSet = [NSCharacterSet letterCharacterSet];
//
//    if ([firstAlphabet rangeOfCharacterFromSet:alphabetSet].location == NSNotFound
//        || ![self isNumbersOnly:restOfTheString]
//        || passport.length != 9) {
//
//        valid = NO;
//    }
//
//    return valid;
//}
//
//+ (BOOL)validPasscode:(NSString *)passcode {
//    return (passcode && passcode.length == 6 && [self isNumbersOnly:passcode]);
//}
//
//+ (BOOL)validPasscode:(NSString *)passcode andConfirmPasscode:(NSString *)confirmPasscode {
//    return (confirmPasscode.integerValue == passcode.integerValue);
//}
//
//+ (BOOL)validMatchingPassword:(NSString *)password confirmPassword:(NSString *)confirmPassword {
//    BOOL valid = NO;
//
//    if ([password isEqualToString:confirmPassword]) {
//        valid = YES;
//    }
//
//    return valid;
//}
//
//+ (BOOL)validAlphanumericPassword:(NSString *)password {
//
//    BOOL valid = YES;
//
//    if (![self isAlphaNumeric:password] || password.length < 8 || password.length > 20 || ![self containNumber:password] || ![self containCharacters:password]) {
//        valid = NO;
//    }
//
//    return valid;
//}
//
//+ (BOOL)isAlphaNumeric:(NSString *)input {
//    NSCharacterSet * unwantedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
//    return ([input rangeOfCharacterFromSet:unwantedCharacters].location == NSNotFound);
//}
//
//+ (BOOL)containNumber:(NSString *)input {
//    NSCharacterSet * numberSet = [NSCharacterSet decimalDigitCharacterSet];
//    return ([input rangeOfCharacterFromSet:numberSet].location != NSNotFound);
//}
//
//+ (BOOL)containCharacters:(NSString *)input {
//    NSCharacterSet * numberSet = [NSCharacterSet letterCharacterSet];
//    return ([input rangeOfCharacterFromSet:numberSet].location != NSNotFound);
//}
//
//+ (BOOL)isNumbersOnly:(NSString *)input {
//    NSCharacterSet * numberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
//    return ([input rangeOfCharacterFromSet:numberSet].location == NSNotFound);
//}

@end
